package web

import (
	"WebFacade/log"
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

var (
	ginServer *http.Server
)

func Init(port int) error {
	handler := gin.Default()
	Template(handler)

	ginServer = &http.Server{
		Addr:         ":" + strconv.Itoa(port),
		Handler:      handler,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
	}

	var err error
	go func() {
		err = ginServer.ListenAndServe()
		if err == nil {
			log.InfoLog("gin server is running", nil)
		} else {
			err = log.ErrorLog(log.ErrorServiceHttp, map[string]interface{}{
				"port": port,
			}, err)
		}
	}()

	return err
}

func StopHttpServer() {
	ctx := context.Background()
	if ginServer != nil {
		if err := ginServer.Shutdown(ctx); err != nil {
			err = log.ErrorLog(log.ErrorServiceHttp, nil, err)
		}
	}
}
